#include <jni.h>
#include <string>
#include "search.h"

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_jni4cpp_JNITest_stringFromJNI(JNIEnv *env, jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

//调用android打印日志
void logFormJni(JNIEnv *env, jobject thiz, jstring value) {
    jclass jc = env->GetObjectClass(thiz);
    //获取方法id,参数1：class对象，参数2：方法名称，参数3：(Ljava/lang/String;)传入参数String，V返回参数void
    jmethodID jmd2 = env->GetMethodID(jc, "mylog", "(Ljava/lang/String;)V");
    //调用log方法打印日志
    env->CallVoidMethod(thiz, jmd2, value);
}

extern "C"
JNIEXPORT void JNICALL
Java_com_example_jni4cpp_JNITest_logFromJNI(JNIEnv *env, jobject thiz, jstring msg) {
    logFormJni(env, thiz, msg);
}

extern "C"
JNIEXPORT void JNICALL
Java_com_example_jni4cpp_JNITest_setAgeFromJNI(JNIEnv *env, jobject thiz, jint age) {
    //获取jclass对象
    jclass jc = env->GetObjectClass(thiz);
    //获取字段id
    jfieldID jfd = env->GetFieldID(jc, "age", "I");
    env->SetIntField(thiz, jfd, age);
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_example_jni4cpp_JNITest_getAgeFromJNI(JNIEnv *env, jobject thiz) {
    //获取jclass对象
    jclass jc = env->GetObjectClass(thiz);
    //获取字段id, "()I"参数为空，返回值为int
    jmethodID jmd = env->GetMethodID(jc, "getAge", "()I");
    jint age = env->CallIntMethod(thiz, jmd);
    return age;
}

jstring int2string(JNIEnv *env, int num) {
    char buf[256];
    sprintf(buf, "%d", num);
    jstring str = env->NewStringUTF(buf);
    return str;
}

extern "C"
JNIEXPORT jint JNICALL
Java_com_example_jni4cpp_JNITest_sequenceSearchFromJNI(JNIEnv *env, jobject thiz, jobjectArray arr,
                                                       jint key) {
    if (arr == NULL) return -1;

    int len = env->GetArrayLength(arr);
    Element element[len];
    for (int i = 0; i < len; i++) {
        jobject obj = env->GetObjectArrayElement(arr, i);
        jclass jc = env->GetObjectClass(obj);
        jmethodID jmd = env->GetMethodID(jc, "intValue", "()I");
        int number = env->CallIntMethod(obj, jmd);
        //注意要指针接收
        Element *elem = &element[i];
        elem->num = number;
    }

    SSTable table = {element, len};
    for (int i = 0; i < table.length; i++) {
        Element elem = table.element[i];
        jstring str = int2string(env, elem.num);
        logFormJni(env, thiz, str);
    }
    Element elemKey = {key};
    //传递地址值给指针才能指向原来的对象（引用传递），而不能单纯的用引用接收（值传递）
    int index = sequenceSearch(&table, &elemKey);
//    int index = sequenceSearch2(table, elemKey);

    return index;

}